﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace TTCaller
{
    public enum PanelType { Main, Msg, SysConfig, DispatchAsk, SReport, Input, Login };
    public partial class Form_Main : Form
    {

        bool m_bRunCmd = false;
        Queue m_qRecvCmd = new Queue();

        CallerLoginPanel m_clp;
        MainScreenPanel m_msp;
        BoxStatus m_bs;
        SysConfigPanel m_scp;
        SendAndWaitPanel m_sawp;
        ShowMsgPanel m_smp;

        JobConfirmPanel m_jcp;
        JobCancelPanel m_jcep;
        MsgListPanel m_mlp;
        PrepareCallTaxiPanel m_pctp;
        static public Form_Main Main = null;

        public bool m_bLogined = false;
        public string m_strIMEI = "000000000000000";
        public string m_strAddr = "測試地址";
        public string m_strFuncControl = "0";
        public string m_strTel = "27510000";

        public bool IsSupportTaxi
        {
            get
            {
                if (m_strFuncControl == "2" || m_strFuncControl == "3")
                {
                    return true;
                }
                return false;
            }
        }
        public bool IsCallTaxi
        {
            get
            {
                if (m_strFuncControl == "1" || m_strFuncControl == "3")
                {
                    return true;
                }
                return false;
            }
        }

        public string StartLoc = "";

        public string m_strLastCallTaxiCount = "0";

        public bool IsSendAndWait { get { return m_sawp.Visible; } }

        public void SetTopMost(bool arg_b)
        {
            this.TopMost = arg_b;
        }

        public void ReLogin(string arg_strANS)
        {
            m_clp.ReLogin(arg_strANS);
        }
        
        

        public Form_Main()
        {



            InitializeComponent();
            StartLoc = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName) + "\\";




            m_qRecvCmd = new Queue();
            m_bRunCmd = false;
            Main = this;

            DeviceManager.setBackLightTimeOut(StoreData.getInstance().BackLightSecs);
            DeviceManager.setVolume(StoreData.getInstance().SoundVol);
            DeviceManager.setBackLightValue(StoreData.getInstance().BackLightLevel);


            this.WindowState = FormWindowState.Maximized;
           // CmdTalker.getInstance().initial();
            m_bs = new BoxStatus(); 
            this.Controls.Add(m_bs);
            m_clp = new CallerLoginPanel();
            this.Controls.Add(m_clp);
            m_msp =new MainScreenPanel();

            this.Controls.Add(m_msp);
            m_jcep = new JobCancelPanel();
            this.Controls.Add(m_jcep);
            m_smp = new ShowMsgPanel();
            this.Controls.Add(m_smp);
            m_mlp = new MsgListPanel();
            this.Controls.Add(m_mlp);

            //this.Controls.Add(m_st);
            m_sawp = new SendAndWaitPanel();
            this.Controls.Add(m_sawp);
            m_scp = new SysConfigPanel();
            m_scp.Visible = true;
            m_scp.BringToFront();
            m_scp.Visible = false;
            this.Controls.Add(m_scp);



            m_jcp = new JobConfirmPanel();
            this.Controls.Add(m_jcp);

            m_pctp = new PrepareCallTaxiPanel();
            this.Controls.Add(m_pctp);



            m_bs.Left = (this.Width - m_bs.Width);
            m_bs.BringToFront();
            m_bs.Visible = true;

            CmdTalker.getInstance().initial();
            //CmdTalker.getInstance().SendCMD("AT$MSGQCL");

            ChangeToLogin();

            //ChangeUIFace(Color.White, Color.Black);

            //this.m_bs.BringToFront();
            //this.m_bs.Left = this.Width - this.m_bs.Width;
            //m_st.BringToFront();
            //m_lp.BringToFront();


            
            this.timer_Checker.Enabled = true;
            this.resetBackLightTimeout();

            
        }

        public void ChangeUIFace(Color arg_cFore, Color arg_cBack)
        {

            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                    UIUtility.ChangeFace(c, arg_cFore, arg_cBack);
            }
        }
        public void DisableUIButton()
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                    UIUtility.ButtonControl(c, false);
            }
        }
        public void EnableUIButton()
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                    UIUtility.ButtonControl(c, true);
            }
        }
        public void ChangeToShowMsg(string arg_strMsg)
        {
            m_smp.Visible = true;
            m_smp.BringToFront();
            m_smp.initial(arg_strMsg, ShowMsgPanel.MsgPanelType.MessageRecv);
            //SetBoxToFront(); 


        }

        public MainScreenPanel Screen_MainScreen { get { return this.m_msp; } }

        public void ShowWaitingPanel()
        {
            DisableUIButton();
            m_sawp.Width = this.Width - 40;
            m_sawp.Left = (this.Width - m_sawp.Width) / 2;
            m_sawp.Top = (this.Height - m_sawp.Height) / 2;
            m_sawp.Visible = true;
            m_sawp.BringToFront();
            this.Refresh();
        }

        public void HideWaitingPanel()
        {
            m_sawp.Visible = false;
            m_sawp.SendToBack();
            this.Refresh();
            EnableUIButton();
        }





        private void HideAllPanel()
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                {
                    c.Visible = false;
                }
            }
        }


        public void ChangeToMainScreen()
        {
            HideAllPanel();
            m_msp.Visible = true;
            m_msp.BringToFront();
            Screen_MainScreen.disableButtonOneSec();
            Screen_MainScreen.initial();
            SetBoxToFront(); 

            //TODO: 091230 訊息完, 先暫不切回來, 不然會很卡..
            //CheckNaviStatus();
        }

        public void ChangeToLogin()
        {
            HideAllPanel();
            m_clp.Visible = true;
            m_clp.BringToFront();
            m_clp.initial();

            SetBoxToFront();
        }

        public void SetBoxToFront()
        {
            m_bs.Left = (this.Width - m_bs.Width);
            m_bs.BringToFront();
            m_bs.Visible = true;
        }

        public void ChangeToMsgList(MsgType arg_my)
        {
            HideAllPanel();
            m_mlp.Visible = true;
            m_mlp.BringToFront();
            m_mlp.initial(arg_my);
            //SetBoxToFront();
        }

        public void ChangeToMessageRead(string arg_strCMD)
        {
            m_smp.Visible = true;
            m_smp.BringToFront();
            m_smp.initial(arg_strCMD, ShowMsgPanel.MsgPanelType.MessageRead);
            //SetBoxToFront();
        }

        public void ChangeToJobCancel(string arg_strTemp,MsgType arg_mt)
        {
            m_jcep.initial(arg_strTemp, arg_mt);
            m_jcep.Visible = true;
            m_jcep.BringToFront();
            //SetBoxToFront();
        }

        public void ChangeToJobConfirm(string arg_strData)
        {
            HideAllPanel();
            m_jcp.Visible = true;
            m_jcp.BringToFront();
            m_jcp.initial(arg_strData);
            SetBoxToFront();
        }
        public void ChangeToPrepareCallTaxi()
        {
            HideAllPanel();
            m_pctp.Visible = true;
            m_pctp.BringToFront();
            m_pctp.initial();
            SetBoxToFront();
        }



        public void SetNoTaxiPanel(string arg_str, int arg_nSecs, bool arg_bShowButton, string arg_strOrderID)
        {
            m_pctp.NoTaxiMsg(arg_str, arg_nSecs, arg_bShowButton, arg_strOrderID);
        }


        public void ChangeToSysConfig()
        {
            HideAllPanel();
            m_scp.Visible = true;
            m_scp.BringToFront();
            //SetBoxToFront();
        }



        public void setBoxStatus(BoxStatusItem arg_bsi, bool arg_bShow)
        {
            switch (arg_bsi)
            {

                case BoxStatusItem.Server:
                    m_bs.setServerStatus(arg_bShow);
                    break;

            }
        }

        

        public bool getBoxStatus(BoxStatusItem arg_bsi)
        {
            switch (arg_bsi)
            {
                case BoxStatusItem.Server:
                    return m_bs.ServerStatus;
            }
            return false;
        }

        public void addCmdToQueue(string arg_strCmd)
        {

            lock (m_qRecvCmd)
            {
                m_qRecvCmd.Enqueue(arg_strCmd);
            }

        }

        DateTime dtCheckBox = System.DateTime.Now;
        DateTime dtCheckBoxAcc = System.DateTime.Now;
        DateTime dtLastServerCheck = System.DateTime.Now;

        string strLastInputStatus = "22222222";
        public void updateLastServerCheck()
        {
            dtLastServerCheck = System.DateTime.Now.Add(new TimeSpan(0, 15, 0));
        }
        int nCMDIndex = 0;

        DateTime dtLastSetSystemDT = System.DateTime.Now;
        

        DateTime dtBackLightTimeout = System.DateTime.Now.AddSeconds(DeviceManager.readBackLightTimeOut());

        public void resetBackLightTimeout()
        {
            dtBackLightTimeout = System.DateTime.Now.AddSeconds(DeviceManager.readBackLightTimeOut());
            DeviceManager.setBackLightOn();
        }


       // DateTime m_dtCheckOnTop = System.DateTime.Now.AddSeconds(3);
        private void timer_Checker_Tick(object sender, EventArgs e)
        {
            try
            {

                this.button_Close.BringToFront();
                this.button_Log.BringToFront();

                CmdTalker.getInstance().doGPRSCheck();

                if (this.dtBackLightTimeout < System.DateTime.Now)
                {
                   // DeviceManager.setBackLightOff();
                    dtBackLightTimeout = System.DateTime.Now.AddSeconds(DeviceManager.readBackLightTimeOut());
                }
                

                string strServerCMD = "";
                if (m_bLogined)
                {
                    if (!m_sawp.Visible)
                    {

                        strServerCMD = CmdTalker.getInstance().checkServerCMD("J");
                        if (strServerCMD != "")
                        {

                            //更新叫車記錄


                            switch (strServerCMD[1])
                            {
                                case 'F':
                                case 'P':
                                    Form_Main.Main.ChangeToJobConfirm(strServerCMD);

                                    //設定系統時間..
                                    //SetSysTime(strServerCMD.Substring(4, 12));

                                    break;

                                case 'N':
                                    string strJNOrderID = "";
                                    if (strServerCMD.Length > 18)
                                    {
                                        strJNOrderID = strServerCMD.Substring(3, 15);
                                    }
                                    LogManager.getInstance().Log("JNOID:" + strJNOrderID);
                                    Form_Main.Main.SetNoTaxiPanel("抱歉, 目前附近沒有空車, 請稍後再叫. 謝謝您.", 5, true, strJNOrderID);
                                    break;
                                case 'C': //未處理, 應針對回應代碼通知客人是否動作是成功的, 若有N及F要補訊息..說明已取消
                                    string strTemp = "";// "抱歉, 由於您逾時未回應同意用車, 計程車已全部取消.";

                                    string strRow = strServerCMD.Substring(17);
                                    LogManager.getInstance().Log("JC:" + strRow);
                                    while (strRow.Length >= 5)
                                    {
                                        string strHead = strRow.Substring(0, 5);
                                        LogManager.getInstance().Log("Head:" + strHead);

                                        if (strHead[0] == 'N' )
                                        {
                                            strTemp += "計程車 "+ strHead.Substring(1, 4) + " 取消用車失敗. 請來電取消, 謝謝您.";
                                        }
                                        else if( strHead[1] == 'F')
                                        {
                                            strTemp += "計程車 " + strHead.Substring(1, 4) + " 同意用車失敗, 若您仍需用車, 請重新叫車. 謝謝您.";
                                        }
                                        strRow = strRow.Substring(5);
                                    }

                                    if (strTemp != "")
                                    {

                                        Form_Main.Main.ChangeToShowMsg(strTemp);
                                        StoreData.getInstance().addMsg(System.DateTime.Now.ToString("MMddHHmm") + "MR" + strTemp);
                                    }

                                    break;


                            }
                        }

                        strServerCMD = CmdTalker.getInstance().checkServerCMD("CI");

                        if (strServerCMD != "")
                        {
                            Form_Main.Main.resetBackLightTimeout();
                            switch (strServerCMD[2])
                            {
                                case '1':
                                    break;
                                case '2':
                                    break;
                                case '0':
                                    break;
                            }
                        }


                        strServerCMD = CmdTalker.getInstance().checkServerCMD("P");

                        if (strServerCMD != "")
                        {
                            Form_Main.Main.resetBackLightTimeout();
                            string strTemp = "";
                            switch (strServerCMD[1])
                            {
                                case 'P':
                                    updateDispatchRec(strServerCMD.Substring(2, 4), 'P');
                                    strTemp = "計程車 " + strServerCMD.Substring(2, 4) + " 已到定點等候, 請前往搭車. 謝謝.";
                                    Form_Main.Main.ChangeToShowMsg(strTemp);
                                    StoreData.getInstance().addMsg(System.DateTime.Now.ToString("MMddHHmm") + "MR" + strTemp);
                         
                                    break;
                                case 'C':
                                    updateDispatchRec(strServerCMD.Substring(2, 4), 'D');
                                    strTemp = "計程車 " + strServerCMD.Substring(2, 4) + " 已久候放棄, 若仍需用車, 請重新叫車. 謝謝.";

                                    Form_Main.Main.ChangeToShowMsg(strTemp);
                                    StoreData.getInstance().addMsg(System.DateTime.Now.ToString("MMddHHmm") + "MR" + strTemp);

                                    break;
                                case 'M':
                                    updateDispatchRec(strServerCMD.Substring(2, 4), 'P');
                                    strTemp = "計程車 " + strServerCMD.Substring(2, 4) + " 已到定點等候多時, 請儘速前往搭車. 謝謝.";

                                    Form_Main.Main.ChangeToShowMsg(strTemp);
                                    StoreData.getInstance().addMsg(System.DateTime.Now.ToString("MMddHHmm") + "MR"+ strTemp);

                                    break;
                                case 'U':
                                    updateDispatchRec(strServerCMD.Substring(2, 4), 'U');
                                    break;
                            }
                        }

                        strServerCMD = CmdTalker.getInstance().checkServerCMD("M");

                        if (strServerCMD != "")
                        {
                            Form_Main.Main.resetBackLightTimeout();
                            switch (strServerCMD[1])
                            {
                                case 'R':
                                    Form_Main.Main.ChangeToShowMsg(strServerCMD.TrimEnd().Substring(2, strServerCMD.Length - 3));

                                    StoreData.getInstance().addMsg(System.DateTime.Now.ToString("MMddHHmm") + strServerCMD.TrimEnd().Substring(0,strServerCMD.Length -1));

                                    break;
                            }
                        }

                    }


                    

                    strServerCMD = CmdTalker.getInstance().checkServerCMD("T");
                    if (strServerCMD != "")
                    {
                        Form_Main.Main.resetBackLightTimeout();
                        switch (strServerCMD[1])
                        {

                            case 'J':

                                //逾時未回應用車..
                                Form_Main.Main.ChangeToMainScreen();

                                string strTemp = "抱歉, 由於您逾時未回應同意用車, 計程車已全部取消.";

                                Form_Main.Main.ChangeToShowMsg(strTemp);
                                StoreData.getInstance().addMsg(System.DateTime.Now.ToString("MMddHHmm") + "MR" + strTemp);

                                break;

                            case 'T':
                                //設定系統時間..                                
                                SetSysTime(strServerCMD.Substring(2, 12));
                                break;



                            //更改參數及時間
                            case '0':
                                StoreData.getInstance().RealTimeButtonMins = strServerCMD.Substring(3);
                                break;

                            case '3':
                                StoreData.getInstance().MissPnrExtendMins = System.Convert.ToInt32(strServerCMD.Substring(3));
                                break;
 
                        }
                    }


                }



                strServerCMD = CmdTalker.getInstance().checkServerCMD("S");
                if (strServerCMD != "")
                {
                    Form_Main.Main.resetBackLightTimeout();
                    switch (strServerCMD[1])
                    {
                        case 'A'://No Function
                            Form_Main.Main.m_strFuncControl = strServerCMD.Substring(2, 1);
                            Form_Main.Main.m_strAddr = strServerCMD.Substring(3, strServerCMD.Length - 4);
                            SoundManager.getInstance().playWelcome();

                            Form_Main.Main.m_bLogined = true;
                            Form_Main.Main.ChangeToMainScreen();
                            break;

                        case 'E':
                            
                            Form_Main.Main.ChangeToLogin();
                            break;

                    }
                }



    


                
            }
            catch (Exception ex)
            {
                if (button_Log.Visible)
                {
                    MessageBox.Show(ex.Message);
                    string strStackT = ex.StackTrace;
                    int nLen = strStackT.Length;
                    MessageBox.Show(ex.StackTrace.Substring(0, nLen / 2));
                    MessageBox.Show(ex.StackTrace.Substring(nLen / 2));
                }
            }

        }
        public string getBodyText(string arg_strOri)
        {

            //JA01100316153532000001ND            
            try
            {
                //LogManager.getInstance().Log("GBT:" + arg_strOri);
                if (arg_strOri[0] == 'J')
                {
                    return "呼號 " + arg_strOri.Substring(18, 4) + ",約 " + arg_strOri.Substring(22, 3).TrimStart('0') + " 分鐘";// arg_strOri.Substring(arg_nTextStart, nLastLen);
                }
                else if (arg_strOri[0] == 'P')
                {
                    return "呼號 " + arg_strOri.Substring(18, 4) + ",已定點";
                }
                else if (arg_strOri[0] == 'U')
                {
                    return "呼號 " + arg_strOri.Substring(18, 4) + ",已載客";
                }
                else if (arg_strOri[0] == 'D')
                {
                    return "呼號 " + arg_strOri.Substring(18, 4) + ",駕駛久候已放棄.";
                }
                else
                {
                    return "呼號 " + arg_strOri.Substring(18, 4) + ",已取消";
                }
            }
            catch (Exception ex)
            {
                return "錯誤:" + ex.Message;
            }
        }

        public void updateDispatchRec(string arg_strCallNo, char arg_cTag)
        {
            ArrayList alNew = new ArrayList();
            ArrayList alData =  StoreData.getInstance().getDispatch();
            bool bFound = false;
            for (int i = 0; i < alData.Count; i++)
            {
                string strTemp = (string)alData[i];
                if (!bFound && strTemp.Length > 25 && strTemp.Substring(18, 4) == arg_strCallNo)
                {
                    LogManager.getInstance().Log("UDR:" + strTemp + ":" + arg_strCallNo + ":" + arg_cTag);
                    strTemp = arg_cTag + strTemp.Substring(1);
                    bFound = true;
                }
                alNew.Add(strTemp);
            }

            StoreData.getInstance().setDispatchData(alNew);
            
        }


        public void button_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }




        public void button_Log_Click(object sender, EventArgs e)
        {
            if (System.Convert.ToString(this.button_Log.Tag) != "Y")
            {
                this.button_Log.Tag = "Y";


                string strTemp = LogManager.getInstance().getLog();
                while (strTemp != "")
                {
                    this.listBox_Log.Items.Insert(0, strTemp);
                    strTemp = LogManager.getInstance().getLog();
                }

                while (this.listBox_Log.Items.Count > 300)
                    this.listBox_Log.Items.RemoveAt(this.listBox_Log.Items.Count - 1);
                
                
                this.listBox_Log.Visible = true;
                this.listBox_Log.BringToFront();


            }
            else
            {
                this.button_Log.Tag = "N";
                this.listBox_Log.Visible = false;
                this.listBox_Log.SendToBack();
            }
        }

        private void Form_Main_LostFocus(object sender, EventArgs e)
        {
            

        }


        private void SetSysTime(string strCmd)
        {
            //if (dtLastSetSystemDT < System.DateTime.Now)
            {
                LogManager.getInstance().Log("set SysTime:" + strCmd);

                if (strCmd.Length == 12)
                {
                    LogManager.getInstance().Log("set SysTime in:" + strCmd);

                    DeviceManager.SYSTEMTIME st = new DeviceManager.SYSTEMTIME();


                    st.wYear = System.Convert.ToUInt16("20" + strCmd.Substring(0, 2));
                    st.wMonth = System.Convert.ToUInt16(strCmd.Substring(2, 2));
                    st.wDay = System.Convert.ToUInt16(strCmd.Substring(4, 2));
                    st.wHour = System.Convert.ToUInt16(strCmd.Substring(6, 2));
                    st.wMinute = System.Convert.ToUInt16(strCmd.Substring(8, 2));
                    st.wSecond = System.Convert.ToUInt16(strCmd.Substring(10, 2));
                    st.wMilliseconds = 0;

                    DateTime dt = new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
                    LogManager.getInstance().Log("get SysTime:" + dt.ToString("yy/MM/dd HH:mm:ss"));
                    dt = dt.AddHours(-8);


                    st.wYear = System.Convert.ToUInt16(dt.Year);
                    st.wMonth =  System.Convert.ToUInt16(dt.Month);
                    st.wDay =  System.Convert.ToUInt16(dt.Day);
                    st.wHour =  System.Convert.ToUInt16(dt.Hour);
                    st.wMinute = System.Convert.ToUInt16( dt.Minute);
                    st.wSecond = System.Convert.ToUInt16( dt.Second);
                    

                    DeviceManager.SetSystemTime(ref st);
                    CmdTalker.getInstance().UpdateSystem();
                    Form_Main.Main.setBoxStatus(BoxStatusItem.Server, true);

                    //DateTime dt = new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);

                    dtLastSetSystemDT = dtLastSetSystemDT.AddHours(24);

                    LogManager.getInstance().Log("set SysTime:" + dt.ToString("yy/MM/dd HH:mm:ss"));
                }
            }

        }

        /* 設定全螢幕
        protected override void OnLoad(EventArgs e)
        {

            SHFullScreen(this.Handle, SHFS_HIDETASKBAR |
                SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON);

            base.OnLoad(e);
        }

        private const int SHFS_SHOWTASKBAR = 0x0001;
        private const int SHFS_HIDETASKBAR = 0x0002;
        private const int SHFS_SHOWSIPBUTTON = 0x0004;
        private const int SHFS_HIDESIPBUTTON = 0x0008;
        private const int SHFS_SHOWSTARTICON = 0x0010;
        private const int SHFS_HIDESTARTICON = 0x0020;

        [DllImport("aygshell")]
        static extern bool SHFullScreen(IntPtr hwnd, int dwState);
         */
    }
}